//
//  IndexController.swift
//  flowerpot
//
//  Created by fyname on 15/9/18.
//  Copyright © 2015年 senhe. All rights reserved.
//

import UIKit

class IndexController: UIViewController , UITableViewDataSource,UITableViewDelegate,UMSocialUIDelegate{
    
    var window: UIWindow?
 
    
    @IBOutlet weak var indexTableView: UITableView!
    
    //var leftViewController:UIViewController!
    var num:Int = 0
    
    // default datas
    var datas:Int = 0
    
    var listVideos : NSMutableArray!

    override func viewDidLoad() {
        super.viewDidLoad()

        num = 5
        
        if (num > 0) {
            self.tabBarItem.badgeValue = "sdfas"
        }else{
            self.tabBarItem.badgeValue = nil
        }

        
        // Do any additional setup after loading the view.
        
        let bundle = NSBundle.mainBundle()
        let plistPath : String! = bundle.pathForResource("videos", ofType: "plist")
        listVideos = NSMutableArray(contentsOfFile: plistPath)
        
        
        weak var weakSelf = self as IndexController
        
        // 上拉动画
        self.indexTableView.headerViewRefreshAnimationStatus(.headerViewRefreshArrowAnimation, images: [])
        
        self.indexTableView.hiddenFooterView()
        // 上啦加载更多
        self.indexTableView.toLoadMoreAction({ () -> () in
            print("toLoadMoreAction success")
            if (weakSelf?.datas < 10){
                weakSelf?.datas += 10
                weakSelf?.indexTableView.reloadData()
                weakSelf?.indexTableView.doneRefresh()
            }else{
                weakSelf?.indexTableView.endLoadMoreData()
            }
        })
        
        // 及时上拉刷新
        indexTableView.nowRefresh({ () -> Void in
            weakSelf?.delay(2.0, closure: { () -> () in})
            weakSelf?.delay(2.0, closure: { () -> () in
                print("nowRefresh success")
                weakSelf?.datas += 10
                self.indexTableView.showFooterView()
                weakSelf?.indexTableView.reloadData()
                weakSelf?.indexTableView.doneRefresh()
            })
        })
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    @IBAction func IndexShare(sender: AnyObject) {
        
        //注意：分享到微信好友、微信朋友圈、微信收藏、QQ空间、QQ好友、来往好友、来往朋友圈、易信好友、易信朋友圈、Facebook、Twitter、Instagram等平台需要参考各自的集成方法
        UMSocialSnsService.presentSnsController(self, appKey: Common.UMkey, shareText: "@友盟分享测试啦!", shareImage: UIImage(named:("xingxing_yellow"))!, shareToSnsNames: [UMShareToSina,UMShareToTencent,UMShareToWechatSession,UMShareToWechatTimeline,UMShareToQzone,UMShareToQQ], delegate: self)
        
        //UMSocialSnsService.presentSnsIconSheetView(self, appKey:"56557a2467e58e59910005fb", shareText:"很好玩的小游戏,小时都玩过吧!https://github.com/c-shen", shareImage: UIImage(named:"xingxing_yellow"), shareToSnsNames: [UMShareToSina,UMShareToWechatSession,UMShareToWechatTimeline,UMShareToTencent,UMShareToRenren,UMShareToDouban, UMShareToFacebook,UMShareToLine, UMShareToQzone,UMShareToQQ], delegate: self)
    }

    @IBAction func ClickSetting(sender: AnyObject) {
        print("click menu")
        Common.rootViewController.showLeft()
    }
    
    
    override func viewWillAppear(animated: Bool){
        super.viewWillAppear(animated)
        MobClick.beginLogPageView("Index")
    }
    override func viewDidAppear(animated: Bool){
        super.viewWillDisappear(animated)
        MobClick.endLogPageView("Index")
    }
    
    // MARK: - Table view data source
    //返回节的个数
     func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Potentially incomplete method implementation.
        // Return the number of sections.
        return 1
    }
    //返回某个节中的行数
     func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete method implementation.
        // Return the number of rows in the section.
        return listVideos.count
    }
    //为表视图单元格提供数据，该方法是必须实现的方法
     func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cellIdentifier : String = "indexCell"
        let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! IndexCell
        let row = indexPath.row
        let rowDict : NSDictionary = listVideos.objectAtIndex(row) as! NSDictionary
        let url : String = rowDict.objectForKey("video_img") as! String
        let dataImg : NSData = NSData(contentsOfURL: NSURL(string : url)!)!
        //cell.JieVideoImg.image = UIImage(data: dataImg)

        cell.indexImage.image = UIImage(data: dataImg)
        cell.indexName.text = rowDict.objectForKey("video_title") as? String
        cell.indexLove.text = rowDict.objectForKey("video_subTitle") as? String
        cell.indexTime.text = "刚刚"
        return cell
        
    }
    
    
    func delay(delay:Double, closure:()->()) {
        dispatch_after(
            dispatch_time(
                DISPATCH_TIME_NOW,
                Int64(delay * Double(NSEC_PER_SEC))
            ),
            dispatch_get_main_queue(), closure)
    }
    
    func didFinishGetUMSocialDataInViewController(response:UMSocialResponseEntity){
        //根据`responseCode`得到发送结果,如果分享成功
        if(response.responseCode == UMSResponseCodeSuccess)
        {
            //得到分享到的微博平台名
            log.debug("分享成功!")
        }else{
            log.debug("分享失败!")
        }
    }

}
